package com.func;

import com.Server;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WeightedPolling extends Request {

    private int sunWeight = 0;
    private Map<Server, Integer> currentMap = new HashMap<>();

    public WeightedPolling() {
        super();
        List<Server> list = getList();
        System.out.println("初始化权重获取");
        System.out.println("===============================");
        list.forEach(server -> {
            currentMap.put(server, 0);
            sunWeight += server.getWeight();
            System.out.printf("服务器: %s, 当前权重: %s%n", server.getName(), 0);
        });
    }

    @Override
    Server getServer() {
        List<Server> list = getList();
        list.forEach(server -> {
            currentMap.put(server, currentMap.get(server) + server.getWeight());
        });
        // 获取 currentMap 里 value最大的 Server
        int maxCurrentWeight = 0;
        Server maxServer = null;
        for (Server server : currentMap.keySet()) {
            if (currentMap.get(server) > maxCurrentWeight) {
                maxCurrentWeight = currentMap.get(server);
                maxServer = server;
            }
        }
        currentMap.put(maxServer, maxCurrentWeight-sunWeight);
        System.out.println("===============================");
        System.out.println("当前权重");
        list.forEach(server -> System.out.printf("服务器: %s, 当前权重: %s%n", server.getName(), currentMap.get(server)));
        return maxServer;
    }



}

